#pragma once

#include <iostream>
#include <memory>
#include <string>
#include <sys/epoll.h>
#include "Sock.hpp"
#include "Epoller.hpp"
#include "NoCopy.hpp"

uint32_t EVENT_IN = (EPOLLIN);
uint32_t EVENT_OUT = (EPOLLOUT);

class EpollServer : public NoCopy
{
    static const int num = 64;

public:
    EpollServer(uint16_t port)
        : _port(port)
        , _listensocket_ptr(new Sock())
        , _epoller_ptr(new Epoller())
    {
    }

    ~EpollServer()
    {
        _listensocket_ptr->Close();
    }

    void Init()
    {
        _listensocket_ptr->Socket();
        _listensocket_ptr->Bind(_port);
        _listensocket_ptr->Listen();

        std::cout << "create listen socket success, fd:" << _listensocket_ptr->Fd() << std::endl;
        //printf("create listen socket success, fd:%d",_listensocket_ptr->Fd());
    }

    void Accepter()
    {
        std::string clientip;
        uint16_t clientport;
        // 接受连接,不会阻塞,返回连接的套接字
        int sock = _listensocket_ptr->Accept(&clientip, &clientport);
        if (sock > 0)
        {
            // 把该套接字加入到epoll模型的红黑树中
            _epoller_ptr->EpollUpdate(EPOLL_CTL_ADD, sock, EVENT_IN);
            std::cout << "get a new link ,clientip:" << clientip << "clientport:" << clientport << std::endl;
            //printf("get a new link, client info@ %s:%d", clientip.c_str(), clientport);
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get a message: " << buffer << std::endl;

            // write
            std::string echo_string = "echo_string $";
            echo_string += buffer;
            write(fd, echo_string.c_str(), echo_string.size());
        }
        else if (n == 0)
        {
            // 对端关闭了套接字,所以要将套接字从epoll模型的红黑树中删除,此套接字必须合法
            std::cout << "sockfd close ,fd:" << fd << std::endl;
            _epoller_ptr->EpollUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            std::cout << "read failed ,fd:" << fd << std::endl;
            _epoller_ptr->EpollUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

    void Dispatcher(struct epoll_event revs[],int num)
    {
        // 从就绪队列上提取的事件，需要先遍历，判断是什么事件就绪
        for (int i = 0; i < num; i++)
        {
            // 获取事件以及fd
            uint32_t events = revs[i].events;
            int fd = revs[i].data.fd;
            if (events & EVENT_IN)
            {
                // 有两种可能1.连接事件就绪2.读事件就绪
                if (fd == _listensocket_ptr->Fd())
                {
                    // 接受连接
                    Accepter();
                }
                else
                {
                    // 读事件
                    Recver(fd);
                }
            }
            else if (events & EVENT_OUT)
            {
            }
            else
            {
            }
        }
    }

    void Start()
    {
        // 先将listensocket 添加到epoll模型中的红黑树中
        _epoller_ptr->EpollUpdate(EPOLL_CTL_ADD, _listensocket_ptr->Fd(), EVENT_IN);

        struct epoll_event revs[num];
        while (1)
        {
            int n = _epoller_ptr->EpollWait(revs, num); // revs输出型参数。告诉我们有几个fd上的事件就绪，按顺序排列挂在就绪队列上
            if (n > 0)
            {
                // 有n个fd上的事件就绪
                std::cout << "event happened,fd:" << revs[0].data.fd << std::endl;
                // 分发n个事件
                Dispatcher(revs,n);
            }
            else if (n == 0)
            {
                std::cout << "time out..." << std::endl;
            }
            else
            {
                std::cout << "epoll wait failed " << std::endl;
            }
        }
    }

private:
    std::shared_ptr<Sock> _listensocket_ptr;
    std::shared_ptr<Epoller> _epoller_ptr;
    uint16_t _port;
};
